package com.better.common.jwtauth.TokenManager;


import com.better.common.jwtauth.secruity.JWTUserDetails;
import com.better.common.jwtauth.secruity.JwtTokenUtil;
import com.better.common.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 通过Redis存储和验证token的实现类
 *
 * @author:
 * @date :2017/12/7
 */
@Component
public class RedisTokenManager implements TokenManager {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.loginExpiration}")
    private Long loginExpiration;

    @Override
    public String generateAccessToken(JWTUserDetails userDetails) {
        String token = jwtTokenUtil.generateAccessToken(userDetails);
        //redisUtils.set(token, token, this.loginExpiration);
        RedisTokenInfo redisTokenInfo = new RedisTokenInfo(userDetails.getUsername(), token);
        redisUtils.setJson(token, redisTokenInfo, this.loginExpiration);
        return token;
    }

    @Override
    public boolean checkToken(String token) {
        return redisUtils.hasKey(token);
    }

    @Override
    public void refreshToken(String key,  RedisTokenInfo redisTokenInfo) {
        redisUtils.setJson(key, redisTokenInfo, this.loginExpiration);

    }

    @Override
    public String generateRefreshToken(JWTUserDetails userDetails) {
        String token = jwtTokenUtil.generateAccessToken(userDetails);
        return token;
    }

    @Override
    public void deleteToken(String token) {
        redisUtils.del(token);
    }

    @Override
    public RedisTokenInfo getRealToken(String token) {
        return redisUtils.getJson(token, RedisTokenInfo.class);
    }
}
